<template>
  <el-dialog :title="title || '题库'" :visible.sync="show" @close="handleClose"
    :width="creatTestlet || selectQuestionGroup || studyCourse || testQuestionGroup ? '95vw' : '1200px'" center
    :close-on-click-modal="false">
    <iframe :src="iframeRouter" width="100%" frameborder="0" ref="iframeDom" class="iframe" :class="{ isLoad: isLoad }"
      v-if="(foreignID || creatTestlet || selectQuestionGroup || isVote) && show"></iframe>
    <div v-else>题组ID不存在</div>
  </el-dialog>
</template>

<script>
import { location_QuestionBank, location } from "@/util/tool";
import { Session } from '@/util/storage/session.js'
import { mapState } from "vuex";
export default {
  data() {
    return {
      isLoad: false,
      show: false,
      params: {},
      dom: null,
    };
  },
  props: {
    title: String,
    iframeShow: Boolean,
    iframeRouter: String,
    foreignID: Number,
    sitem: Object,
    studyCourse: Boolean, // 学习系统刷题
    // creativeCourse: Boolean, // 创作系统
    isReview: Boolean, // 按学生批阅页面
    creatTestlet: Boolean, // 创建题组页面
    testQuestionGroup: Boolean, // 测试题组
    selectQuestionGroup: Boolean, // 选择题组
    isMarking: Boolean, // 是否是批阅状态
    isVote: Boolean, // 是否是投票
    stuUserID: Number, // 批阅学生的userID
    designCourseInfo: Object,
    currNo: Number,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    getCurrGuidelineData() {
      // 在找到的任务组中通过当前任务的任务编号找到任务 studyCourse
      let thistaskNoInGroup = this.getLocalStorageTaskData({
        taskID: this.$parent.taskID,
      });
      if (!thistaskNoInGroup) return undefined;
      thistaskNoInGroup.taskGroupID = this.$parent.taskGroupID;
      return thistaskNoInGroup;
    },
  },
  watch: {
    iframeShow(n) {
      if (n) {
        this.show = n;
        // if (this.studyCourse) return
        if (this.studyCourse && !this.foreignID && !this.isVote) return
        this.$nextTick(() => {
          this.listenIframeOnload();
        });
      } else {
        window.removeEventListener("message", this.addListenFn)
      }
    },
  },
  methods: {
    handleClose() {
      this.show = false
      this.$emit("handleIframeClose");
    },
    /**
     * @description 监听iframe加载完成
     */
    listenIframeOnload() {
      const that = this;
      const iframe = this.$refs.iframeDom;
      // 处理兼容行问题
      if (iframe.attachEvent) {
        iframe.attachEvent("onload", function () {
          that.isLoad = true;
          that.sendData(iframe);
          that.completeLoad = true;
        });
      } else {
        iframe.onload = function () {
          that.isLoad = true;
          that.sendData(iframe);
          that.completeLoad = true;
        };
      }
    },
    /**
     * otherWindow.postMessage(message, targetOrigin, [transfer]);
     * https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
     * @description 向iframe发送消息
     */
    async sendData(dom) {
      let userInfoCookie = null;
      const res = await Session.get('userInfo', true)
      const eTime = Session.get('userInfo__expires__', false)
      userInfoCookie = res;
      if (!userInfoCookie)
        return this.$antdMessage.error({
          content: "身份信息已过期！",
        });
      this.isLoad = false;
      let params = {
        cookie: null,
        userInfo: this.userInfo,
        isStudy: false,
        taskDetail: { guidelineResults: {} },
        currGuidelineID: null,
        iframeID: +new Date() + "" || "defaultIframeID",
      }
      // 是否是批阅状态
      params.userInfo.isMarking = this.isMarking ? true : false
      if (this.creatTestlet) {
        params.courseInfo = {}
        Object.assign(params.courseInfo, this.designCourseInfo)
      }
      // 创作系统测试题组
      if (this.testQuestionGroup) {
        const gitem = this.$parent.gitem;
        const taskDetail = {
          guidelineResults: {},
        };
        taskDetail.guidelineResults[gitem.guidelineID] = gitem;
        params = Object.assign(params, {
          cookie: null,
          isStudy: true,
          taskDetail: taskDetail,
          currGuidelineID: gitem.guidelineID,
          testMode: true,
        });
        res.testMode = true
      }
      // 按学生批阅查看刷题记录
      if (this.isMarking) {
        params = Object.assign(params, {
          // isReview: true,
          width: this.width || undefined,
          currGuidelineID: this.foreignID,
        });
        params.userInfo.stuUserID = this.stuUserID
        params.userInfo.isMarking = true
        params.taskDetail.guidelineResults[this.sitem.guidelineID] = {
          session_id: this.sitem.session_id,
        };
        res.stuUserID = this.stuUserID
        res.isMarking = true
        console.log(params);
      }
      // 是否是在学习系统刷题
      if (this.studyCourse) {
        params = Object.assign(params, {
          cookie: null,
          isStudy: true,
          taskDetail: this.studyCourse
            ? this.getCurrGuidelineData :
            { guidelineResults: {} },
          currGuidelineID: this.$parent.guidelineObj.guidelineID,
        });
      }
      // 投票
      if (this.isVote) {
        params = Object.assign(params, {
          isVote: true,
          userInfo: this.userInfo
        })
      }
      // 设置userInfo
      let getLocalTime = 1;
      const sessionTime = sessionStorage.getItem('userInfo__expires__', false)
      const now = new Date().getTime()
      if (sessionTime && sessionTime > now) getLocalTime = Math.ceil((sessionTime - now) / 1000 / 60 / 60) || 1;
      Session.set('userInfo', res, true, Math.floor(60 * getLocalTime))

      this.params = params
      this.dom = dom
      dom.contentWindow.postMessage(
        JSON.stringify(params),
        location_QuestionBank(window)
      );
      // dom.contentWindow.postMessage(
      //   JSON.stringify(params),
      //   "http://localhost:3000"
      // );
      window.addEventListener("message", this.addListenFn, false);
    },
    getLocalStorageTaskData(data) {
      const currNo = this.currNo;
      let myStudyData = localStorage.getItem("studyData")
        ? JSON.parse(localStorage.getItem("studyData"))
        : {};
      let getCurrStudyData = myStudyData[currNo]?.[this.userInfo.userID];
      let currTaskData = getCurrStudyData?.find(
        (item) => item.taskID == data.taskID
      );
      return currTaskData;
    },
    // this.addListenFn
    /**
     * @description 监听来自 iframe 的消息
     * @param {MessageEvent} event - 消息事件
     */
    addListenFn(event) {
      console.log('[message] 收到消息：', event);

      const locationPath = window.location.origin; // 获取当前页面的 origin，例如 http://localhost:8080
      const trustedOrigins = [
        'http://localhost:8080',    // 本地开发地址
        'http://10.1.6.130',        // 学校 IP 地址
        'http://codelover.club',    // 线上 HTTP 地址
        'https://codelover.club'    // 线上 HTTPS 地址
      ];

      if (!trustedOrigins.includes(event.origin) && event.origin !== locationPath) {
        console.warn('[message] 拒绝不信任的 origin：', event.origin);
        return;
      }

      let data; // ✅ 提前声明变量
      // 尝试解析 event.data
      try {
        if (typeof event.data === 'string') {
          data = JSON.parse(event.data);
          console.log('[message] 已解析 JSON 字符串：', data);
        } else if (typeof event.data === 'object') {
          data = event.data;
          console.log('[message] 已接收到对象数据：', data);
        } else {
          console.warn('[message] 未知类型的 data，忽略：', typeof event.data);
          return;
        }
      } catch (e) {
        console.error('[message] JSON 解析失败：', e, event.data);
        return;
      }
      // 检查 data 是否包含 iframeID
      if (!data.iframeID || data.iframeID !== this.params.iframeID) {
        console.warn(`[message] iframeID 不匹配或缺失（当前=${this.params.iframeID}，收到=${data.iframeID}），忽略`);
        return;
      }

      // ✅ 学习系统 - 题库交卷后的 message 回调
      if (this.studyCourse) {
        if ((data.score && data.score !== '-8') && data.session_id) {
          console.log('[message] 处理 handleUpdateTaskScore');
          this.$emit("handleUpdateTaskScore", data.score, this.dom, this.params, data.session_id);
          return;
        }
        if (data.session_id) {
          console.log('[message] 处理 handleUpdateSessionID');
          this.$emit("handleUpdateSessionID", data.session_id, this.dom, this.params);
        }
      }

      // ✅ 创作系统 - 创建题组成功回调
      if (this.creatTestlet) {
        console.log('[message] 处理 createdTestlet');
        this.$emit("createdTestlet", data.testLetData);
        this.show = false;
        this.$emit("handleIframeClose");
      }

      // ✅ 选择题组回调
      if (this.selectQuestionGroup) {
        console.log('[message] 处理 saveTestlet');
        this.show = false;
        this.$emit("saveTestlet", data.testLetData);
      }

      // ✅ 投票系统回调
      if (this.isVote) {
        console.log('[message] 处理 saveVoteInfo');
        this.$emit("saveVoteInfo", data);
        this.show = false;
        this.$emit("handleIframeClose");
      }
    }
  },
  mounted() {
    this.show = this.iframeShow
    // if (this.foreignID) this.listenIframeOnload();
  },
  destroyed() {
    window.removeEventListener("message", this.addListenFn)
  }
};
</script>


<style lang="stylus" scoped>
.iframe {
  // width: 779px;
  height: 80vh;
}

.isLoad {
  height: 100%;
}
</style>